<style scoped>
</style>
<!-- 编辑文件 设置的弹窗 -->
<template>
  <div class="edit-file-dialog">
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-press-escape="false"
      :close-on-click-modal="false" width="960px" @close="close" :top="'5vh'">
      <ACEDefault ref="fileCode" :mode="mode" :maxLines="27"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="onSubmit()">保 存</el-button>
        <el-button type="success" size="small" @click="onSubmitAndClose()">保存并关闭</el-button>
        <el-button @click="dialogFormVisible = false" size="small">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ACEDefault from '@/components/common/ace/Default.vue'
export default {
  data () {
    return {
      maxSize: 1024 * 1024,
      loading: true,
      title: '',
      dialogFormVisible: false,
      filepath: null,
      scode: {
        content: null
      },
      mode: 'text'
    }
  },
  methods: {
    show (title, path, suffix) {
      if (!path) {
        return
      }
      // 初始化数据
      this.dialogFormVisible = true
      this.title = title
      this.filepath = path
      if (suffix === 'html' || suffix === 'htm') {
        this.mode = 'html'
      } else if (suffix === 'xml') {
        this.mode = 'xml'
      } else if (suffix === 'css') {
        this.mode = 'css'
      } else if (suffix === 'js') {
        this.mode = 'javascript'
      } else {
        this.mode = 'text'
      }
      this.loading = true

      this.$nextTick(() => {
        this.$refs['fileCode'].created()
      })
      // 请求后台获取数据
      this.$post('/virtual-folder/file', { filepath: this.filepath }).then(response => {
        if (response) {
          this.scode.content = response.content ? response.content : ''
          this.$refs['fileCode'].loaded()
          this.$refs['fileCode'].setValue(this.scode.content)
        }
        this.loading = false
      })
    },
    onSubmit (callback) {
      // 提交表单
      this.scode.content = this.$refs['fileCode'].getValue()

      if (this.scode.content.length > this.maxSize) {
        this.$message.error('代码不能超过 ' + this.maxSize + ' 个字符')
        return
      }

      this.loading = true
      this.$post('/virtual-folder/save-file', {filepath: this.filepath, content: this.scode.content}).then(response => {
        if (response) {
          if (typeof callback === 'function') {
            callback()
          }
        }
        this.loading = false
      })
    },
    close () {
      this.loading = true
      this.title = ''
      this.scode = {
        content: null
      }
    },
    onSubmitAndClose () {
      this.onSubmit(() => {
        this.dialogFormVisible = false
      })
    }
  },
  components: {
    ACEDefault
  }
}

</script>
